import 'dart:io';

import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:path_provider/path_provider.dart';
import 'package:flutter_syt/generated/l10n.dart';
import 'package:flutter_syt/utils/click_utils.dart';
import 'package:flutter_syt/utils/utils_dlog.dart';
import 'package:flutter_syt/widgets/loading_widget.dart';
import 'package:flutter_syt/widgets/view_state_widget.dart';
// import 'package:flutter_full_pdf_viewer/full_pdf_viewer_scaffold.dart';
import 'package:syncfusion_flutter_pdfviewer/pdfviewer.dart';

// class PDFScreen extends StatelessWidget {
//   final String pathPDF;
//   final String title;
//   PDFScreen(this.pathPDF, {this.title = ''});

//   @override
//   Widget build(BuildContext context) {
//     // SfPdfViewer./
//     return Scaffold(
//         appBar: AppBar(
//           title: Text(title),
//         ),
//         body: SfPdfViewer.network(
//           pathPDF,
//           canShowPaginationDialog: false,
//         ));
//   }
// }

class PDFScreen extends StatefulWidget {
  final String pathPDF;
  final String title;
  PDFScreen(this.pathPDF, {this.title = ''});
  @override
  PDFScreenState createState() => PDFScreenState();
}

class PDFScreenState extends State<PDFScreen> {
  late Future _future;
  String savePath = '';
  String directoryPath = '';
  String? error;
  bool isLoading = true;
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: _buildMain(),
      // body: FutureBuilder(
      //   future: _future,
      //   builder: (context, snapshot) {
      //     if (snapshot.error != null) {
      //       return Container(
      //         color: Colors.white,
      //         child: TextButton(
      //           child: ViewStateEmptyWidget(
      //             message: S().network_error,
      //           ),
      //           onPressed: ClickUtils.debounce(() async {
      //             // DLog('casdvds');
      //             downloadPDF();
      //           }),
      //         ),
      //       );
      //     } else {}
      //     if (snapshot.connectionState == ConnectionState.done) {
      //       return SfPdfViewer.file(
      //         File(savePath),
      //         canShowPaginationDialog: false,
      //       );
      //     } else {
      //       return LoadingWidget();
      //     }
      //   },
      // )
    );
  }

  Widget _buildMain() {
    if (isLoading) {
      return LoadingWidget();
    } else if (error != null) {
      return Container(
        color: Colors.white,
        child: TextButton(
          child: ViewStateEmptyWidget(
            message: S().network_error,
          ),
          onPressed: ClickUtils.debounce(() async {
            // DLog('casdvds');
            // if (mounted) {
            //   setState(() {
            //     isLoading = true;
            //     error = null;
            //   });
            // }
            error = null;
            deleAndDownload();
            // downloadPDF(isCheck: false);
          }),
        ),
      );
    } else {
      return SfPdfViewer.file(
        File(savePath),
        canShowPaginationDialog: false,
        onDocumentLoadFailed: (details) async {
          DLog(details);
          deleAndDownload();
        },
      );
    }
  }

  Future delDir(FileSystemEntity file) async {
    if (file is Directory) {
      final List<FileSystemEntity> children = file.listSync();
      for (final FileSystemEntity child in children) {
        await delDir(child);
      }
    }
    try {
      await file.delete();
    } catch (e) {
      print('删除了基本目录没有权限，暂不处理');
    }
  }

  deleAndDownload() async {
    isLoading = true;
    if (mounted) {
      setState(() {});
    }
    FileSystemEntity entity = Directory(directoryPath);
    try {
      await delDir(entity);
    } catch (e) {
      DLog('错误 $e');
    }
    await Future.delayed(Duration(seconds: 1));
    downloadPDF(isCheck: false);
  }

  downloadPDF({bool isCheck = true}) async {
    directoryPath = await getSavePath('/Download/');
    savePath = directoryPath + widget.pathPDF.split('/').last;
    // DLog(savePath);
    // Directory(savePath).delete()
    bool isDownload = false;
    if (isCheck == true) {
      isDownload = await File(savePath).exists();
    }

    // DLog(isOpen);
    if (isDownload == false) {
      try {
        await Dio().download(
          widget.pathPDF,
          savePath,
          onReceiveProgress: (count, total) {
            DLog("DASDa  $count,   $total");
          },
        );
      } catch (e) {
        error = S().network_error;
        // return Future.error(S().network_error);
      }
    }

    isLoading = false;
    if (mounted) {
      setState(() {});
    }
  }

  Future<String> getSavePath(String endPath) async {
    Directory tempDir = await getTemporaryDirectory();
    String path = tempDir.path + endPath;
    Directory directory = Directory(path);
    if (!directory.existsSync()) {
      directory.createSync(recursive: true);
    }
    return path;
  }

  @override
  void initState() {
    super.initState();
    // getDownloadsDirectory();
    _future = downloadPDF();
    // getTemporaryDirectory();
  }

  @override
  void dispose() {
    super.dispose();
  }

  @override
  void didUpdateWidget(PDFScreen oldWidget) {
    super.didUpdateWidget(oldWidget);
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
  }
}
